<template>
  <div>
    <!-- 导航栏 -->
     <Back title="景点详情" />
    <!-- 图 -->
    <van-image
  
              width="100%"
  
              height="200px"
  
              :src="attinfo1?.img ? `http://127.0.0.1:8000${attinfo1.img}` : images"
  
              alt="特惠图片"
  
              class="special-image"
  
            />
    <!-- 景点信息 -->
    <van-cell-group class="custom-group">
      <van-cell>
        <template #title>
          <div class="title">
            <span>{{ attinfo1?.name || "青城山" }}</span>
            <span class="rating">{{ attinfo1?.rating || "5A" }}</span>
          </div>
        </template>
      </van-cell>
      <van-cell>
        <template #title>
          <div class="info">
            <span class="score">{{ attinfo1?.score || "4.8分" }}</span>
            <span class="comments">3124条评论</span>
          </div>
        </template>
      </van-cell>
      <van-cell>
        <template #title>
          <div class="info">
            <span class="time">营业时间：8:00~17:30</span>
          </div>
        </template>
      </van-cell>
      <van-cell>
        <template #title>
          <div class="info">
            <span class="address">{{
              attinfo1?.desc || "四川省成都市都江堰市青城山镇青城山路"
            }}</span>
          </div>
        </template>
      </van-cell>
      <van-cell>
        <template #title>
          <div class="info">
            <span class="phone">{{ attinfo1?.phone || "028-88888889" }}</span>
          </div>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 门票预订 -->
    <van-tabs v-model:active="activeTab">
      <van-tab title="门票">
        <van-cell-group>
          <van-cell
            v-for="(ticket, index) in tickets"
            :key="index"
            :title="ticket.name"
          >
            <template #label>
              <div class="price">
                <span class="original">{{ ticket?.originalPrice || ticket.price*1.2}}</span>
                <span class="current">{{ ticket.price }}</span>
              </div>
            </template>
            <van-button
              type="primary"
              size="small"
              @click="bookTicket(ticket.id,ticket.name)"
            >
              预定
            </van-button>
          </van-cell>
        </van-cell-group>
        <!-- 缆车信息 -->
        <!-- <van-cell-group title="缆车">
          <van-cell
            v-for="(cableCar, index) in cableCars"
            :key="index"
            :title="cableCar.name"
          >
            <template #label>
              <div class="price">
                <span class="original">{{ cableCar.originalPrice }}</span>
                <span class="current">{{ cableCar.currentPrice }}</span>
              </div>
            </template>
            <van-button
              type="primary"
              size="small"
              @click="bookCableCar(cableCar.name)"
            >
              预定
            </van-button>
          </van-cell>
        </van-cell-group> -->
      </van-tab>

      <van-tab title="点评">
        <!-- 评论按钮 -->
        <van-button type="primary" @click="showPopup">发表评论</van-button>

        <!-- 弹窗组件 -->
        <van-popup
          v-model:show="showComment"
          round
          position="bottom"
          :style="{ height: '50%' }"
        >
          <div class="comment-box">
            <!-- 输入区域 -->
            <van-field
              v-model="commentText"
              rows="4"
              autosize
              type="textarea"
              placeholder="写下你的评论..."
              class="input-area"
            />

            <!-- 图片预览 -->
            <div v-if="previewImages.length" class="preview-container">
              <van-image
                v-for="(img, index) in previewImages"
                :key="index"
                :src="img"
                width="80"
                height="80"
                class="preview-img"
                @click="removeImage(index)"
              >
                <template #extra>
                  <van-icon name="clear" class="delete-icon" />
                </template>
              </van-image>
            </div>

            <!-- 底部操作栏 -->
            <div class="action-bar">
              <van-button
                icon="photo-o"
                type="primary"
                plain
                @click="triggerFileInput"
              >
                添加图片
              </van-button>
              <van-button type="primary" @click="submitComment">确认发表</van-button>
            </div>

            <!-- 隐藏的文件输入 -->
            <input
              ref="fileInput"
              type="file"
              multiple
              accept="image/*"
              style="display: none"
              @change="handleFileUpload"
            />
          </div>
        </van-popup>

        <van-cell-group>
          <van-cell
            v-for="(review, index) in reviews"
            :key="index"
            titlestyle="display: inline"
          >
            <template #title>
              <van-image
                round
                width="40"
                height="40"
                :src="review.user.img ? `http://127.0.0.1:8000${review.user.img}` :review.userAvatar"
              />
              <div class="user-rating-row" style=" float: right;">
                <span class="username">{{ review?.userName  || review.user.name || "匿名用户"}}</span>
                <van-rate
                  v-model="review.score"
                  readonly
                  allow-half
                />
              </div>
            </template>

            <template #label>
              <div class="content-text">
                <van-text-ellipsis
                  rows="3"
                  :content="review.content"
                  expand-text="展开"
                  collapse-text="收起"
                />
              </div>
              <div class="likes">
                {{ review.likes }}点赞
                <span style="color: dodgerblue; cursor: pointer" @click="showReplyBox(review)">回复</span>
              </div>
              <div v-if="review.showReplyBox" class="reply-box">
                <van-field
                  v-model="replyText"
                  placeholder="输入回复内容"
                />
                <van-button type="primary" size="small" @click="submitReply(review)">发送</van-button>
              </div>
              <div v-for="(subComment, subIndex) in review.subComments" :key="subIndex" class="sub-comment">
                <van-image
                  round
                  width="40"
                  height="40"
                  :src="subComment.userAvatar"
                />
                <div class="sub-comment-content">
                  <span class="sub-comment-user">{{ subComment.userName }}</span>
                  <p>{{ subComment.content }}</p>
                </div>
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import http from "../http";
import { Toast } from "vant";

const router = useRouter();
const route = useRoute();
// 景点信息

// 图片轮播数据
const images = ref('https://cdn8.axureshop.com/demo2024/1628102/images/%E6%99%AF%E7%82%B9%E5%88%97%E8%A1%A8/u1111.svg');
const attinfo1=ref({});
const getatt=()=>{
  http.get('/att/att/info/?attractionid='+route.query.id).then(res=>{
    attinfo1.value=res.data.data;
    images.value='http://127.0.0.1:8000'+res.data.img;
  })
}


// 门票数据
const tickets = ref([
  { name: "成人票", originalPrice: "¥80", price: "¥78" },
  { name: "儿童票", originalPrice: "¥40", price: "¥40" },
  { name: "学生票", originalPrice: "¥40", price: "¥40" },
]);

// // 缆车数据
// const cableCars = ref([
//   { name: "单程直通车", originalPrice: "¥30", price: "¥16" },
//   { name: "往返直通车", originalPrice: "¥60", price: "¥31" },
// ]);

// 用户评价数据
const reviews = ref([
  {
    userName: "美女莎莎",
    content: "离成都很近，周末过去放松非常合适，空气好，景色优美！离成都很近，周末过去放松非常合适，空气好，景色优美",
    score: 4.5,
    likes: 99,
    subComments: [], // 子评论数组
    showReplyBox: false, // 是否显示回复框
  },
  {
    userName: "美女莎莎",
    content: "离成都很近，周末过去放松非常合适，空气好，景色优美！",
    score: 5,
    likes: 99,
    subComments: [],
    showReplyBox: false,
  },
  {
    userName: "美女莎莎",
    content: "离成都很近，周末过去放松非常合适，空气好，景色优美！",
    score: 5,
    likes: 99,
    subComments: [],
    showReplyBox: false,
  },
]);
// 获取门票数据
const getticket = () => {
  http.get("/att/ticket/list/",{params:{'attid':route.query.id}}).then((res) => {
    tickets.value = res.data.data;
  });
};
// 获取评价数据
const getReviews = () => {
  http.get("/att/review/list/",{params:{'attid':route.query.id}}).then((res) => {
    reviews.value = res.data.data;
  });
};


// 当前选中的标签
const activeTab = ref(0);

// 返回按钮点击事件
import Back from '../utils/Back.vue';

// 预定门票点击事件
const bookTicket = (ticketid,ticketname) => {
  router.push({
    path: '/order/create',
    query: {
      attractionId: route.query.id,
      attname:attinfo1.value.name ,
      ticketType: '门票',
      productName: ticketname,
      ticket_id: ticketid,
      price: tickets.value.find(t => t.name === ticketname)?.price
    }
  });
};

// 预定缆车点击事件
// const bookCableCar = (cableCarName) => {
//   router.push({
//     path: '/order/create',
//     query: {
//       attractionId: route.query.id,

//       ticketType: '缆车',
//       productName: cableCarName,
//       price: cableCars.value.find(c => c.name === cableCarName)?.currentPrice.replace('¥','')
//     }
//   });
// };

const showComment = ref(false);
const commentText = ref("");
const previewImages = ref([]);
const fileInput = ref(null);

// 打开弹窗
const showPopup = () => {
  showComment.value = true;
};

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click();
};

// 处理文件上传
const handleFileUpload = (e) => {
  const files = e.target.files;
  if (files.length + previewImages.value.length > 3) {
    showToast("最多上传3张图片");
    return;
  }

  Array.from(files).forEach((file) => {
    if (!file.type.startsWith("image/")) {
      showToast("请选择图片文件");
      return;
    }
    const reader = new FileReader();
    reader.onload = (event) => {
      previewImages.value.push(event.target.result);
    };
    reader.readAsDataURL(file);
  });
};

// 删除图片
const removeImage = (index) => {
  previewImages.value.splice(index, 1);
};

// 提交评论
const submitComment = () => {
  if (!commentText.value.trim() && previewImages.value.length === 0) {
    showToast("评论内容或图片不能为空");
    return;
  }

  // 提交逻辑（示例）
  console.log("评论内容:", commentText.value);
  console.log("图片列表:", previewImages.value);

  // 重置表单
  commentText.value = "";
  previewImages.value = [];
  showComment.value = false;
};

// 显示回复框
const showReplyBox = (review) => {
  review.showReplyBox = !review.showReplyBox;
};

// 回复内容
const replyText = ref("");

// 提交回复
const submitReply = (review) => {
  if (!replyText.value.trim()) {
    Toast("回复内容不能为空");
    return;
  }
  const newSubComment = {
    id: Date.now(),
    userName: "当前用户",
    userAvatar: "https://xxx/user.jpg",
    content: replyText.value,
    time: "刚刚",
  };
  review.subComments.push(newSubComment);
  replyText.value = "";
  review.showReplyBox = false;
};

onMounted(() => {
  // 页面加载时的初始化操作
  getatt();
  getticket();
  getReviews();
});
</script>

<style scoped>
/* 景点信息样式 */
.title {
  font-size: 20px;
  font-weight: bold;
}

.rating {
  color: #ff9900;
  margin-left: 10px;
}

.info {
  margin: 10px 0;
}

.score {
  color: #ff9900;
  font-size: 18px;
}

.comments {
  font-size: 14px;
  color: #666;
}

.time {
  font-size: 14px;
  color: #666;
}

.address {
  font-size: 14px;
  color: #666;
}

.phone {
  font-size: 14px;
  color: #666;
}

/* 门票和缆车价格样式 */
.price {
  font-size: 14px;
  color: #666;
}

.original {
  text-decoration: line-through;
  margin-right: 10px;
}

.current {
  color: #ff4400;
  font-weight: bold;
}

/* 用户评价样式 */
.likes {
  font-size: 12px;
  color: #666;
  margin-left: 10px;
}

.reply-box {
  display: flex;
  gap: 8px;
  margin-top: 10px;
}

.sub-comment {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.sub-comment-content {
  flex: 1;
}

.sub-comment-user {
  font-weight: bold;
  margin-bottom: 5px;
}

/* 评论样式优化 */
.user-rating-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  flex-shrink: 0;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.content-text {
  margin-top: 6px;
  line-height: 1.5;
  color: #666;
}

.action-bar {
  margin-top: 8px;
  font-size: 12px;
}

/* 评论图片样式 */
.review-image {
  width: 100%;
  height: auto;
  border-radius: 8px;
  margin-top: 8px;
}

/* 子评论样式 */
.sub-comment {
  margin-left: 20px;
  border-left: 2px solid #eee;
  padding-left: 12px;
}

.sub-comment-user {
  color: #666;
  font-size: 14px;
}

.sub-comment-content p {
  margin: 8px 0;
  color: #666;
  font-size: 14px;
}
</style>